package org.teremail.message.builder;

import org.teremail.message.Content;
import org.teremail.message.ContentHeaders;
import org.teremail.message.SimpleEntity;


public class SimpleEntityBuilder implements ContentEntityBuilder {

    private Content content;
    private final SimpleEntity original;
    private boolean hasChanged = false;
    private String id;
    private final ContentHeadersBuilder contentHeadersBuilder;
    
    public SimpleEntityBuilder(SimpleEntity original,
            ContentHeadersBuilder contentHeadersBuilder) {
        this.original = original;
        this.contentHeadersBuilder = contentHeadersBuilder;
    }
    
    public SimpleEntityBuilder(ContentHeadersBuilder contentHeadersBuilder) {
        this(null, contentHeadersBuilder);
    }
    
    public SimpleEntityBuilder() {
        this(null, new ContentHeadersBuilder());
    }

    public SimpleEntityBuilder(String type, String subType) {
        this();
        contentHeadersBuilder.setContentType(type, subType);
    }
    
    public SimpleEntityBuilder(SimpleEntity simpleEntity) {
        this(simpleEntity, new ContentHeadersBuilder(simpleEntity.getContentHeader()));
    }

    public void setId(String id) {
        hasChanged = true;
        this.id = id;
    }
    
    public SimpleEntityBuilder setContent(Content content) {
        this.content = content;
        hasChanged = true;
        return this;
    }

    public boolean hasChanged() {
        return hasChanged || original == null;
    }    
    
    public SimpleEntity build() {
        if (hasChanged()) {
            ContentHeaders header = contentHeadersBuilder.build();
            return new SimpleEntity(id, header, content);
        } else {
            return original;
        }
    }

    public void setContentHeaders(String contentHeaders) {
        contentHeadersBuilder.load(contentHeaders);
    }

    public String getId() {
        return id;
    }

    public boolean isMultipart() {
        return false;
    }

}
